#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using PHMEE.EntityFrameworkCore;

namespace PHMEE.EnergyEfficiency;

public class TimeSeriesDataLogRepository : ITimeSeriesDataLogRepository
{
    private readonly PHMEEDbContext _context;

    public TimeSeriesDataLogRepository(PHMEEDbContext context)
    {
        _context = context;
    }
    
    public async Task<TimeSeriesDataLog?> FindOrDefaultAsync(Guid id)
    {
        return await _context.TimeSeriesDataLogs.FindAsync(id);
    }
    
    public async Task<TimeSeriesDataLog> InsertAsync(TimeSeriesDataLog timeSeriesDataLog)
    {
        var entityEntry = await _context.TimeSeriesDataLogs.AddAsync(timeSeriesDataLog);
        await _context.SaveChangesAsync();
        return entityEntry.Entity;
    }
    
    public async Task<List<TimeSeriesDataLog>> GetListUnSyncedOperationTimeAscAsync(CancellationToken cancellationToken)
    {
        return await _context.TimeSeriesDataLogs
            .Where(x => x.IsSynced == false)
            .OrderBy(x => x.OperationTime)
            .ToListAsync(cancellationToken: cancellationToken);
    }
    
    // UpdateAsync
    public async Task<TimeSeriesDataLog> UpdateAsync(TimeSeriesDataLog timeSeriesDataLog, CancellationToken cancellationToken)
    {
        var entityEntry = _context.TimeSeriesDataLogs.Update(timeSeriesDataLog);
        await _context.SaveChangesAsync(cancellationToken);
        return entityEntry.Entity;
    }
}